package com.putao.album.tag;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.tag.adapter.TagAlbumPhotoAdapter;
import com.putao.album.tag.bean.TagAlbumPhotoItem;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.putao.album.widget.pullrefresh.PullToRefreshBase;
import com.putao.album.widget.pullrefresh.PullToRefreshGridView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by jidongdong on 15/4/29.
 * <p/>
 * 批量移除该标签相册中的照片
 */
public class ActivityTagAlbumPhotoRemove extends BaseActivity {
    private Button btn_remove;
    private TextView title_tv;
    private List<TagAlbumPhotoItem> mDataList = new ArrayList<TagAlbumPhotoItem>();
    private TagAlbumPhotoAdapter mTagAlbumPhotoAdapter;
    private String mTagName;
    private int mSelectnum = 0;
    private PullToRefreshGridView gv_photolist;
    private String nextPage = "1";
    private boolean mIsLastPage = false;
    private boolean mIsRefreshing = false;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_tag_album_photo_remove;
    }

    @Override
    public void doInitSubViews(View view) {
        btn_remove = queryViewById(R.id.btn_remove, true);
        setPageTitle();
        queryViewById(R.id.back_btn, true);
        gv_photolist = queryViewById(R.id.gv_photolist);
        queryViewById(R.id.right_btn).setVisibility(View.GONE);
        gv_photolist.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        gv_photolist.getRefreshableView().setNumColumns(2);
//        gv_photolist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<GridView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<GridView> gridViewPullToRefreshBase) {
//                updateData();
//            }
//        });
        gv_photolist.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                updateData();
            }
        });
        EventBus.getDefault().register(this);
    }


    @Override
    public void doInitData() {
        initData();
        mTagAlbumPhotoAdapter = new TagAlbumPhotoAdapter(mContext, mDataList);
        mTagAlbumPhotoAdapter.setDeleteMode(true);
        gv_photolist.setAdapter(mTagAlbumPhotoAdapter);
        mTagAlbumPhotoAdapter.notifyDataSetChanged();
        updateData();
    }

    void initData() {
        mDataList.clear();
        TagAlbumPhotoItem item = new TagAlbumPhotoItem();
        item.Type = TagAlbumPhotoItem.DataType.ADD_TAG_PHOTO;
        mDataList.add(item);
    }


    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_BATCH_ADD_TAG_PHOTO:
                refreshData();
                break;
        }
    }

    void refreshData() {
        nextPage = "1";
        mIsLastPage = false;
        updateData();
    }


    protected void updateData() {
        if (mIsLastPage || mIsRefreshing) {
            gv_photolist.onRefreshComplete();
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("page", nextPage);
        params.put("tag", mTagName);
        params.put("baby_id", CommonUtils.getBabyId());

        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_DELTAG_PHOTO_List, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;
    }

    /**
     * 解析返回的标签相册列表数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("photoList");
        if (list != null) {
            if (nextPage.equals("1")) {
                initData();
            }
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String image_id = o.optString("photo_id");
                    String url = o.optString("photo");
                    int is_selected = o.optInt("is_selected");
                    TagAlbumPhotoItem item = new TagAlbumPhotoItem();
                    item.image_id = image_id;
                    item.image_url = url;
                    item.canRemove = (is_selected == 1) ? true : false;
                    mDataList.add(mDataList.size() - 1, item);
                }
            }
            mTagAlbumPhotoAdapter.notifyDataSetChanged();
        }
        nextPage = data.optString("nextPage");
        gv_photolist.onRefreshComplete();
        mIsRefreshing = false;
        if (nextPage.equals("-1")) {
            mIsLastPage = true;
        }
    }

    /**
     * 单击
     */
    AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TagAlbumPhotoItem item = mDataList.get(position);
            if (item.Type == TagAlbumPhotoItem.DataType.NORMAL) {
                boolean selected = item.selected;
                mDataList.get(position).selected = !selected;
                if (!selected) {
                    mSelectnum++;
                } else {
                    if (mSelectnum > 0)
                        mSelectnum--;
                    else {
                        mSelectnum = 0;
                    }
                }
                setSelectNumText();
                mTagAlbumPhotoAdapter.notifyDataSetChanged();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("tag_name", mTagName);
                bundle.putString("tag_id", "-1");
                ActivityHelper.startActivity(mActivity, ActivityTagAlbumPhotoAdd.class, bundle);
            }

        }
    };

    void doDelPhotoTagBat() {
        final JSONArray photos = new JSONArray();
        for (int i = 0; i < mDataList.size(); i++) {
            if (mDataList.get(i).selected == true) {
                photos.put(mDataList.get(i).image_id);
            }
        }
        if (photos.length() == 0) {
            showToast("请选择要移除标签的照片");
            return;
        }
        MobclickAgent.onEvent(mContext, UmengTouchEvent.REMOVE_LABEL);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("photo_ids", photos.toString());
        params.put("tag", mTagName);
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_BATCH_DELTAG_PHOTO_List, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        showToast("移除成功");
                        JSONObject data = HttpRequestUtil.getResponseData(response);
                        String cover = "";
                        if (data != null) {
                            cover = data.optString("cover");
                        }
                        sendUpdateAlbumEvent(photos.length(), cover);
                        finish();
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    /**
     * 发送标签相册添加的照片数
     *
     * @param photos
     */
    private void sendUpdateAlbumEvent(int photos, String cover) {
        Bundle bundle = new Bundle();
        bundle.putString("tag_name", mTagName);
        bundle.putString("cover", cover);
        bundle.putInt("type", 1);
        bundle.putInt("count", photos);
        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_BATCH_REMOVE_TAG_PHOTO, bundle));
    }


    /**
     * 设置选则的数量
     */
    void setSelectNumText() {
        btn_remove.setText("移除标签\"" + mTagName + "\"  " + mSelectnum + " ");
    }


    void setPageTitle() {
        title_tv = queryViewById(R.id.title_tv);
        if (getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                mTagName = bundle.getString("tag_name", "");
                setSelectNumText();
            }
        }
        title_tv.setText(mTagName);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.btn_remove:
                doDelPhotoTagBat();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
